let watermark = {};
/**
 * 目前只能在AiChatDialog里使用，不可以在其它地方使用，因为现在 remove 的逻辑有问题。
 **/
let setWatermark = (text, sourceBody) => {
  let id =
    Math.random() * 10000 +
    "-" +
    Math.random() * 10000 +
    "/" +
    Math.random() * 10000;

  if (document.getElementById(id) !== null) {
    document.body.removeChild(document.getElementById(id));
  }

  let can = document.createElement("canvas");
  can.width = 240; //设置水印之间的左右间距
  can.height = 160; //设置水印之间的上下间距

  let cans = can.getContext("2d");
  cans.rotate((-20 * Math.PI) / 180);
  cans.font = "15px Vedana";
  cans.fillStyle = "rgba(0, 0, 0, .1)";
  cans.textAlign = "left";
  cans.textBaseline = "top";

  // 绘制多行文字
  const textLines = text.split('\n');
  textLines.forEach((line, index) => {
    cans.fillText(line, can.width / 20, index * 15 + 45); // 调整行高
  });

  let water_div = document.createElement("div");
  water_div.id = id;
  water_div.className = "watermarkClass";
  water_div.style.pointerEvents = "none";
  water_div.style.background =
    "url(" + can.toDataURL("image/png") + ") left top repeat";
  water_div.style.top = "0px";
  water_div.style.bottom = "0px";
  water_div.style.left = "0px";
  water_div.style.right = "0px";
  water_div.style.position = "absolute";
  water_div.style.zIndex = "1000";
  water_div.style.display = "block";
  water_div.style.overflow = "hidden";
  if (sourceBody) {
    sourceBody.appendChild(water_div);
  } else {
    document.body.appendChild(water_div);
  }

  return id;
};

/**
 *  @param:
 *  @text == 水印内容
 *  @sourceBody == 水印添加的位置，不传就是body
 * */
watermark.set = (text, sourceBody) => {
  watermark.remove()
  if (text == "") {
    return;
  }
  setWatermark(text, sourceBody);
  // 监听窗口大小变化事件
  window.onresize = () => {
    watermark.remove()
    if (sourceBody) {
      setWatermark(text, sourceBody);
    }
  };
  // let id = setWatermark(text, sourceBody);
  // setInterval(() => {
  //   if (document.getElementById(id) === null) {
  //     id = setWatermark(text, sourceBody);
  //   }
  // }, 2000);
  // window.onresize = () => {
  //   setWatermark(text, sourceBody);
  // };
};

watermark.remove = ()=> {
  const domArr = Array.from(document.getElementsByClassName("watermarkClass"));
  for (let i = 0; i < domArr.length; i++) {
    const element = domArr[i];
    element.remove();
  }
}

export default watermark;
